package 代码记录.指定公司代码练习记录.面试手撕2024.携程机票改签;

public class Test {
    /**
     * 删除链表的倒数第N个节点方式实现是没问题的
     * 但是测试用例运行报错
     */
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        while (node1 != null){
            System.out.print(node1.val + "-");
            node1 = node1.next;
        }
        System.out.println();
        ListNode head = removeN(2, node1);
        System.out.println();
        while (head != null){
            System.out.print(head.val + "-");
            head = head.next;
        }
    }
    public static ListNode removeN(int n, ListNode head){
        ListNode dummy = new ListNode(Integer.MAX_VALUE);
        ListNode prev = dummy;
        dummy.next = head;
        ListNode fast = head;
        for(int i = 0;i < n;i++){
            fast = fast.next;
        }
        while(fast != null){
            fast = fast.next;
            prev = prev.next;
            head = head.next;
        }
        prev.next = head.next;
        return dummy.next;
    }



    private static class ListNode{
        int val;
        ListNode next;

        public ListNode(int val){
            this.val = val;
            this.next = null;
        }
    }
}
